package com.mmall.controller.portal;


import com.mmall.common.Const;
import com.mmall.common.ResponseCode;
import com.mmall.common.ServerResponse;
import com.mmall.pojo.User;
import com.mmall.service.IUserService;
import com.mmall.utils.CookieUtil;
import com.mmall.utils.JsonUtil;
import com.mmall.utils.RedisPoolUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 */
@Controller
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private IUserService iUserService;

    /**
     * 用户登陆
     *
     * @param username
     * @param password
     * @param session
     * @return
     */
    @RequestMapping(value = "login", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse login(String username, String password, HttpSession session,
                                HttpServletResponse response) {

        String path = session.getServletContext().getRealPath("upload");

        log.info("Current path:"+path);
        log.info("Login sessionId:{}" , session.getId());
        ServerResponse<User> retResponse = iUserService.login(username, password);
        if (retResponse.isSuccess()) {
//            session.setAttribute(Const.CURRENT_USER, response.getData());
            //写入cookie中
            CookieUtil.writeLoginToken(response,session.getId());
            //写入redis中
            RedisPoolUtil.setEx(session.getId(),JsonUtil.objToString(retResponse.getData()),
                    Const.RedisExtime.SESSION_EXTIME);

        }
        return retResponse;
    }

    /**推出
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "logout", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse logout(HttpServletRequest request,HttpServletResponse response) {
//        session.removeAttribute(Const.CURRENT_USER);
        log.info("Logout sessionId:" + request.getSession().getId());
        String loginToken = CookieUtil.readLoginToken(request);
        //删除cookie
        CookieUtil.delLoginToken(request, response);
        //删除redis的缓存
        RedisPoolUtil.del(loginToken);
        return ServerResponse.retSuccess();
    }

    /**
     * 注册
     * @param user
     * @return
     */
    @RequestMapping(value = "register",method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<String> register(User user) {

        return iUserService.register(user);
    }

    /**校验是否有效
     * @param str
     * @param type
     * @return
     */
    @RequestMapping(value = "checkValid",method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse checkValid(String str, String type) {

        return iUserService.checkValid(str,type);
    }

    /**获取用户信息
     * @param request
     * @return
     */
    @RequestMapping(value = "getUserInfo",method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse getUserInfo(HttpServletRequest request) {
//        User user = (User) session.getAttribute(Const.CURRENT_USER);
        log.info("GetUserInfo sessionId:" + request.getSession().getId());
        String loginToken = CookieUtil.readLoginToken(request);
        if (StringUtils.isEmpty(loginToken)) {
            return ServerResponse.retErrorMsg("用户未登录，无法获取信息");
        }
        String userJsonStr = RedisPoolUtil.get(loginToken);
        User user = JsonUtil.stringToObj(userJsonStr, User.class);
        if (user != null) {
            return ServerResponse.retSuccessData(user);
        }
        return ServerResponse.retErrorMsg("用户未登录");
    }

    /**获取密码问题
     * @param username
     * @return
     */
    @RequestMapping(value = "forgetGetQuestion",method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse forgetGetQuestion(String username) {
        return iUserService.selectQuestion(username);
    }

    /** 校验答案
     * @param username
     * @param question
     * @param answer
     * @return
     */
    @RequestMapping(value = "forgetCheckAnswer",method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse forgetCheckAnswer(String username, String question, String answer) {
        return iUserService.checkAnswer(username, question, answer);
    }

    /**重置密码
     * @param username
     * @param newPassword
     * @param forToken
     * @return
     */
    @RequestMapping(value = "forgetResetPassword",method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse forgetResetPassword(String username, String newPassword, String forToken) {
        return iUserService.forgetResetPassword(username, newPassword, forToken);
    }

    /**登陆状态更新密码
     * @param request
     * @param oldPassword
     * @param newPassword
     * @return
     */
    @RequestMapping(value = "resetPassword",method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse resetPassword(HttpServletRequest request, String oldPassword, String newPassword) {
        String loginToken = CookieUtil.readLoginToken(request);
        if (StringUtils.isEmpty(loginToken)) {
            return ServerResponse.retErrorMsg("用户未登录，无法获取信息");
        }
        String userJsonStr = RedisPoolUtil.get(loginToken);
        User user = JsonUtil.stringToObj(userJsonStr, User.class);
        if (user == null) {
            return ServerResponse.retErrorMsg("用户未登陆");
        }
        return iUserService.resetPassword(user, oldPassword, newPassword);
    }

    /**更新用户信息
     * @param request
     * @param user
     * @return
     */
    @RequestMapping(value = "updateInformation",method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse updateInformation(HttpServletRequest request, User user) {
        String loginToken = CookieUtil.readLoginToken(request);
        if (StringUtils.isEmpty(loginToken)) {
            return ServerResponse.retErrorMsg("用户未登录，无法获取信息");
        }
        String userJsonStr = RedisPoolUtil.get(loginToken);
        User currentUser = JsonUtil.stringToObj(userJsonStr, User.class);
        if (currentUser == null) {
            return ServerResponse.retErrorMsg("用户未登陆");
        }
        user.setId(currentUser.getId());
        user.setUsername(currentUser.getUsername());
        ServerResponse response = iUserService.updateInformation(user);
        if (response.isSuccess()) {
//            session.setAttribute(Const.CURRENT_USER,response.getData());
            //重新写入redis中
            RedisPoolUtil.setEx(loginToken,JsonUtil.objToString(response.getData()),
                    Const.RedisExtime.SESSION_EXTIME);

        }
        return response;
    }

    /**获取用户详细信息
     * @param request
     * @return
     */
    @RequestMapping(value = "getInformation",method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse getInformation(HttpServletRequest request) {
        String loginToken = CookieUtil.readLoginToken(request);
        if (StringUtils.isEmpty(loginToken)) {
            return ServerResponse.retErrorMsg("用户未登录，无法获取信息");
        }
        String userJsonStr = RedisPoolUtil.get(loginToken);
        User currentUser = JsonUtil.stringToObj(userJsonStr, User.class);
        if (currentUser == null) {
            return ServerResponse.retErrorCode(ResponseCode.NEED_LOGIN.getCode(), "用户未登陆,需要登陆");
        }
        return iUserService.getInformation(currentUser.getId());
    }
}
